import { loginNestedAppForPhone } from '@/services/api/api-login';
import { parse } from '@/utils/historyUtils';
import { setToken } from '@/utils/token';
import { Spin } from 'antd';
import React, { useEffect } from 'react';
import { history, useLocation, useModel } from 'umi';

export default (): React.ReactNode => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const location = useLocation();

  /** 此方法会跳转到 redirect 参数所在的位置 */
  const goto = () => {
    if (!history) return;

    const { phone, route, entry } = parse(location.search) as {
      phone: string;
      route: string;
      entry: string;
    };

    localStorage.setItem('xtbs_nested_entry', entry);

    loginNestedAppForPhone({ phone }).then(async ({ code, data }) => {
      if (code === 0) {
        if (data.state === 4) {
          setToken(data.satoken);
          const userInfo = await initialState?.fetchUserInfo?.();
          if (userInfo) {
            setInitialState({
              ...initialState,
              currentUser: userInfo,
            });
            setTimeout(() => {
              if (history.replaceState) {
                history.replaceState(null, document.title, route);
                history.go(0);
              } else {
                history.replace(route);
              }
              // history.replace(route);yarn 
            }, 100);
          }
        }
      }
    });
  };

  useEffect(() => {
    goto();
  }, []);

  return (
    <div
      style={{
        textAlign: 'center',
        marginTop: 20,
        marginBottom: 20,
      }}
    >
      <Spin size="large" />
    </div>
  );
};
